package icu.lookyousmileface.nio.basic

import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.util.*
import java.util.function.Consumer

/**
 * @title: NioScatingAndGething
 * @projectName NettyPro
 * @author shenj
 * @date 2020/12/1 13:23
 */
fun main(args: Array<String>): Unit {

    val serverSocketChannel = ServerSocketChannel.open();
    val inetSocketAddress = InetSocketAddress(9948);
    //绑定端口到socket上，并启动
    serverSocketChannel.socket().bind(inetSocketAddress);

    //buffer数组
    val byteBuffer = arrayOfNulls<ByteBuffer>(2)
    byteBuffer[0] = ByteBuffer.allocate(5)
    byteBuffer[1] = ByteBuffer.allocate(3)

    val scoketChannel = serverSocketChannel.accept();
    var messageLight = 8;

    while (true) {

        var byteRead: Int = 0

        while (byteRead < messageLight) {

            var read = scoketChannel.read(byteBuffer)

            println("byteRead:" + read)

            byteRead += read.toInt()

            Arrays.asList<ByteBuffer>(*byteBuffer).stream().map { buffer: ByteBuffer -> "potion:" + buffer.position() + "limit:" + buffer.limit() }.forEach { x: String? -> println(x) }
        }

        Arrays.asList<ByteBuffer>(*byteBuffer).forEach(Consumer { buffer: ByteBuffer -> buffer.flip() })

        var byteWrite: Long = 0;

        while (byteWrite < messageLight) {

            var write = scoketChannel.write(byteBuffer)
            byteWrite += write
        }

        Arrays.asList<ByteBuffer>(*byteBuffer).forEach(Consumer { buffer: ByteBuffer -> buffer.clear() })

        println("byteRead:" + byteRead + "byteWrite:" + byteWrite + "messagelenght:" + messageLight)

    }
}